package com.safe.app.config.init.redis;

import org.apache.commons.lang.StringUtils;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.stereotype.Component;
import redis.clients.jedis.JedisPool;

/**
 * 此内部类就是把application.properties的配置数据，进行读取，
 * 创建JedisConnectionFactory和JedisPool，以供外部类初始化缓存管理器使用
 *
 * @author h2l
 */
@Component
@EnableConfigurationProperties({RedisConfig.class})
public class RedisAutoConfig {


    @Bean
    JedisConnectionFactory jedisConnectionFactory(RedisConfig redisConfig) {
        if (StringUtils.isBlank(redisConfig.getHostName())) {
            throw new RuntimeException("application.properties 'redis.hostName' Can not be empty");
        }
        if (redisConfig.getPort() == 0) {
            throw new RuntimeException("application.properties 'redis.port Can not be empty");
        }
        RedisStandaloneConfiguration redisStandaloneConfiguration = new RedisStandaloneConfiguration();
        redisStandaloneConfiguration.setHostName(redisConfig.getHostName());
        redisStandaloneConfiguration.setPort(redisConfig.getPort());
        redisStandaloneConfiguration.setDatabase(redisConfig.getDatabase());
        redisStandaloneConfiguration.setPassword(redisConfig.getPassword());
        return new JedisConnectionFactory(redisStandaloneConfiguration);
    }

    @Bean
    JedisPool jedisPool(RedisConfig redisConfig) {
        JedisPool jedisPool = new JedisPool();
        redisConfig.setHostName(redisConfig.getHostName());
        redisConfig.setPassword(redisConfig.getPassword());
        redisConfig.setPort(redisConfig.getPort());
        redisConfig.setTimeout(redisConfig.getTimeout());
        return jedisPool;
    }

    @Bean
    RedisServer redisServer() {
        return new RedisServer("open-api:");
    }


}
